package br.com.acs.CameraIP.controller;

import java.io.Serializable;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.security.core.userdetails.User;

import br.com.acs.CameraIP.dao.CameraDao;
import br.com.acs.CameraIP.dao.CameraDaoImp;
import br.com.acs.CameraIP.dao.UsuarioDao;
import br.com.acs.CameraIP.dao.UsuarioDaoImp;
import br.com.acs.CameraIP.model.Camera;
import br.com.acs.CameraIP.model.Usuario;
import br.com.acs.CameraIP.util.FacesUtil;

@Controller("loginController")
@ManagedBean
@SessionScoped
public class LoginController implements Serializable {

	private static final long serialVersionUID = 1L;
	private long idCliente = 0;
	private Usuario usuario;

	public LoginController() {
	}

	public String logar() {
		try {
			FacesContext ctx = FacesContext.getCurrentInstance();
			ctx.getExternalContext().dispatch("/j_spring_security_check");
			ctx.responseComplete();
			HttpSession session = (HttpSession) ctx.getExternalContext()
					.getSession(false);
			session.setAttribute("idCliente", idCliente);
			System.out.println("cliente = " + idCliente);
		} catch (Exception ex) {
			FacesUtil.exibirMensagemErro(ex.getMessage());
			return null;
		}
		return null;
	}

	public String logout() {
		FacesUtil.exibirMensagemAlerta("Sessão finalizada com sucesso");
		try {
			RequestDispatcher dispatcher = FacesUtil.getServletRequest()
					.getRequestDispatcher("/j_spring_security_logout");
			dispatcher.forward(FacesUtil.getServletRequest(),
					FacesUtil.getServletResponse());
			FacesContext.getCurrentInstance().responseComplete();
			FacesUtil.exibirMensagemAlerta("Sessão finalizada com sucesso");
		} catch (Exception ex) {
			FacesUtil.exibirMensagemErro("Erro ao sair do sistema");
			return null;
		}
		return null;
	}

	public FacesContext getFacesContext() {
		return FacesContext.getCurrentInstance();
	}

	public HttpSession getSession() {
		return (HttpSession) getFacesContext().getExternalContext().getSession(
				false);
	}

	public Long PegarClienteLogado() {
		try {
			HttpSession session = (HttpSession) FacesContext
					.getCurrentInstance().getExternalContext()
					.getSession(false);
			return (Long) session.getAttribute("idCliente");
		} catch (Exception ex) {
			FacesUtil.exibirMensagemErro(ex.getMessage());
			return null;
		}
	}

	public void setaCameraClienteLogado() {

		usuario = new Usuario();
		SecurityContext context = SecurityContextHolder.getContext();
		if (context instanceof SecurityContext) {
			Authentication authentication = context.getAuthentication();
			if (authentication instanceof Authentication) {
				usuario.setLogin(((User) authentication.getPrincipal())
						.getUsername());

				UsuarioDao dao = new UsuarioDaoImp();
				Usuario user = dao.getUsuarioPorLogin(usuario.getLogin());

				FacesUtil.setSessionAttribute("usuarioLogado", user);

				CameraDao daoCam = new CameraDaoImp();
				List<Camera> listCam = daoCam.getCameraPorCliente(user.getIdCliente());
					
				if (listCam.size() == 1)
						FacesUtil.setSessionAttribute("multicameras", 0);
				else
					    FacesUtil.setSessionAttribute("multicameras", 1);
				
				FacesUtil.setSessionAttribute("cameraAtiva", listCam.get(0));
				
			}
		}
	}

	public long getIdCliente() {
		return idCliente;
	}

	public void setIdCliente(long idCliente) {
		this.idCliente = idCliente;
	}

	public void addMessage(String summary) {
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
				summary, null);
		FacesContext.getCurrentInstance().addMessage(null, message);
	}
}
